﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
using System.Windows;
using System.Collections;

namespace B1103492
{
    /// <summary>
    /// 本类的构思是程序运行的时候，所有的数据存储在临时变量HiddenSingleInfors。
    /// 开始运行和结束的时候，再读取或者存储到XmlPath对应的文件中。
    /// 使用两个变量，虽然通过一定的设置可以实现撤销功能，但是本文没有实现它。
    /// 本类只提供了有些个对外的函数，实现对数据的封装。
    /// 
    /// 另外，特别注意PhotoRelativeName变量，在存储到文件的时候，为了实现移植，
    /// 文件中：\Information\Photo\1.jpg
    /// 这样就方便整个文件夹的移植。
    /// </summary>
    class LowestData
    {


        private static Hashtable HiddenSingleInfors;
        private static Object classLock = typeof(Hashtable);
        private static string XmlPath = "Information/File/通讯录.xml";

        private static Hashtable singleInfors
        {
            get { return GetInfors(); }
            set { HiddenSingleInfors = value; }
        }


        // 参考代码: [美]Steven John Metsker, Design Patterns in C#,P85,Singletons
        private static Hashtable GetInfors()
        {
            lock (classLock)
            {
                if (HiddenSingleInfors == null)
                {
                    HiddenSingleInfors = new Hashtable();
                }
                return HiddenSingleInfors;
            }
        }

        /// <summary>
        /// 参考程序： 
        /// help里面的Creating XML Readers，
        /// Reading Attributes,
        /// 等内容
        /// </summary>
        /// <returns></returns>
        public static bool readFromXml()
        {
            try
            {
                using (XmlReader reader = XmlReader.Create(XmlPath))
                {
                    // Parse the XML document.  ReadString is used to 
                    // read the text content of the elements.
                    reader.MoveToContent();
                    while (reader.Read())
                    {
                        List<string> all = new List<string>();
                        while (reader.MoveToNextAttribute())
                        {
                            all.Add(reader.Value);
                        }
                        if (all.Count == 11)
                        {
                            singleInfors.Add(all[0],new Informations(all));
                        }
                    }
                }
                return true;
            }
            catch (System.IO.FileNotFoundException)
            {
                MessageBox.Show("你的通讯录为空，或者没有放在\n" 
                    + Environment.CurrentDirectory +"/"+ XmlPath 
                    + "\n文件中,你要自己添加联系人哦！",
                    "提示信息", MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            catch (System.NullReferenceException)
            {
                MessageBox.Show("您的“通讯录.xml”文件格式不对！请参照readme.htm里面的格式修改。",
                   "提示信息", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }

        }

        /// <summary>
        /// 参考程序
        /// http://www.cnblogs.com/bingzisky/archive/2008/08/26/1276875.html
        /// </summary>
        /// <returns></returns>
        public static bool saveToXml()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null);
                doc.AppendChild(dec);
                //创建一个根节点（一级）
                XmlElement root = doc.CreateElement("Information");
                doc.AppendChild(root);
                
                //创建节点（二级）
                foreach (Informations data in singleInfors.Values)
                {
                    XmlElement node = doc.CreateElement("Person");
                    node.SetAttribute("姓名", data.name);
                    node.SetAttribute("学号", data.studentNumber);
                    node.SetAttribute("手机", data.phone);
                    node.SetAttribute("QQ", data.qq);
                    node.SetAttribute("邮箱", data.email);
                    node.SetAttribute("宿舍", data.room);
                    node.SetAttribute("实验室", data.lab);
                    node.SetAttribute("导师", data.master);
                    node.SetAttribute("照片", data.photoRelativeName);
                    node.SetAttribute("家庭住址", data.home);
                    node.SetAttribute("备注", data.ps);
                    root.AppendChild(node);
                }
                
                doc.Save(XmlPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message+"\n数据恢复到打开前的状态",
                    "保存失败",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
                return false;
            }
            return true;
        }

        public static bool psuAddUpdate(Informations infor)
        {
            for (int i = 0; i < singleInfors.Count;i++ )
            {
                if (singleInfors.ContainsKey(infor.name))
                {
                    MessageBoxResult r = MessageBox.Show
                        ("发现已经有相同姓名的个人信息，\n确定要更新吗？",
                        "请您决策",
                        MessageBoxButton.OKCancel,
                        MessageBoxImage.Question, MessageBoxResult.Cancel);
 
                    if(r == MessageBoxResult.Cancel)
                    {
                        return false;
                    }
                    singleInfors.Remove(infor.name);
                    break;
                }
            }
            singleInfors.Add(infor.name,infor);
            return true;
        }

        public static bool psuDelete(Informations infor)
        {
            return psuDelete(infor.name);
        }

        public static bool psuDelete(string Name)
        {
            for (int i = 0; i < singleInfors.Count; i++)
            {
                if (singleInfors.ContainsKey(Name))
                {
                    singleInfors.Remove(Name);
                    return true;
                }
            }
            return false;
        }

        public static bool psuDeleteAll()
        {
            singleInfors = null;
            return true;
        }

        public static Hashtable 
            LinqSelectString(string selectStatement)
        {
           Hashtable selectPersons = new Hashtable();
            if (selectStatement == null)
                return selectPersons;

            // 对查询语句分割，
            string[] sarray = selectStatement.Split(new char[] 
            { ' ', '，', '|', '：', '。', '；', ',', ';', '/', '\\' });

            foreach (Informations si in singleInfors.Values)
            {
                bool Yes = true;
                foreach (var s in sarray)
                {
                    if (!si.ToString().Contains(s))
                    {
                        Yes = false;
                        break;
                    }
                }
                if (Yes)
                {
                    selectPersons.Add(si.name, si);
                }
            }
            return selectPersons;
        }

        public static Hashtable
            LinqSelectString()
        {
            return GetInfors().Clone() as Hashtable;
        }

        public static string[] GetNames()
        {
            string[] Names=new string[singleInfors.Count];
            int i = 0;
            foreach (Informations ifm in singleInfors.Values)
            {
                Names[i] = ifm.name;
                i++;
            }
            return Names;
        }
    }

    public class Informations
    {
        public string name;
        public string studentNumber;
        public string qq;
        public string phone;
        public string email;
        public string room;//宿舍房间
        public string lab;//实验室房间
        public string master;//导师
        public string home;//家庭住址
        public string photoRelativeName;//照片的相对程序的地址
        public string ps; //备注


        public Informations()
            : this("上海交通大学", "B1103492")
        {
        }

        public Informations(List<string> all)
        {
            this.name = all[0];
            this.studentNumber = all[1];
            this.phone = all[2];
            this.qq = all[3];
            this.email = all[4];
            this.room = all[5];
            this.lab = all[6];
            this.master = all[7];
            this.photoRelativeName = all[8];
            this.home = all[9];
            this.ps = all[10];
        }

        public Informations
            (
            string name,
            string studentNumber,
            string qq = null,
            string phone = null,
            string email = null,
            string room = null,
            string lab = null,
            string master = null,
            string photoRelativeName = null,
            string home = null,
            string ps = null
            )
        {
            this.name = name;
            this.studentNumber = studentNumber;
            this.phone = phone;
            this.qq = qq;
            this.email = email;
            this.room = room;
            this.lab = lab;
            this.master = master;
            this.photoRelativeName = photoRelativeName;
            this.home = home;
            this.ps = ps;
        }

        public override string ToString()
        {
            return name + "|"
                + studentNumber + "|"
                + qq + "|"
                + phone + "|"
                + email + "|"
                + room + "|"
                + lab + "|"
                + master + "|"
                + photoRelativeName + "|"
                + home + "|"
                + ps;
        }
    }
}
